import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

import { defalutImg } from '../comm';
import { PromotionShareService } from '../promotion-share.service';

@Component({
  selector: 'app-divide-classify-list',
  templateUrl: './divide-classify-list.component.html',
  styleUrls: ['./divide-classify-list.component.scss']
})
export class DivideClassifyListComponent implements OnInit {

  fallback: string = defalutImg;
  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  /**
   * 新增编辑分类
   * ----------------------------------------------------------------
   */
  isVisible = false;
  modalItem: any = null;
  submitClassLoading = false;
  validateForm!: FormGroup;

  // 游戏添加Modal
  isSelectVisible = false;
  editGameItems: any = {};
  addGameIds: any[] = [];

  constructor(
    private msg: NzMessageService,
    private fb: FormBuilder,
    private services: PromotionShareService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      name: ['', [Validators.required]],
      state: ['', [Validators.required]] // 0 启用 1 禁用 2 删除
    });

    this.loadTable()
  }

  async loadTable() {
    let params = {
      page: 1,
      pageSize: 1000
    }
    this.tableParams.loading = true;
    const {code, data, message}: any = await this.services.getGameTypeList(params);
    this.tableParams.loading = false;

    if (code === 0) {
      this.tableParams.tableData = data || [];
    }
  }

  /**
   * 上移 0 | 下移 1
   * @param item 
   * @param type 
   */
  async moveOrderItem(item: any, type: number) {
    let params = {
      id: item.id,
      moveType: type
    }
    const {code, message}: any = await this.services.moveGameTypeData(params);
    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    }
  }

  // 启用 | 禁用
  async stateChange(item: any) {
    let params = {
      id: item.id,
      state: item.state === 0 ? 1 : 0,
      name: item.name
    }
    const {code, message}: any = await this.services.editGameTypeData(params);
    
    if (code === 0) {
      this.msg.success('状态修改成功');
      this.loadTable();
    }
  }

  // 删除分类
  async deleteItem(item: any) {
    let params = {
      id: item.id,
      state: 2
    }
    const {code, message}: any = await this.services.editGameTypeData(params);
    
    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    }
  }

  /**
   * 新增编辑分类 Modal
   * ----------------------------------------------------------------
   */
  showClassifyModal(item?: any) {
    this.validateForm.reset();
    this.modalItem = item ? item : null;

    if (item) {
      this.validateForm.patchValue({
        name: item.name,
        state: item.state
      })
    }
    this.isVisible = true;
  }

  async submitForm() {
    if (this.validateForm.valid) {
      let params: any = {
        ...this.validateForm.value
      }

      // 编辑ID
      if (this.modalItem) {
        params.id = this.modalItem.id
      }
      this.submitClassLoading = true;
      const {code, message}: any = await this.services.editGameTypeData(params);
      this.submitClassLoading = false;

      if (code === 0) {
        this.msg.success('操作成功');
        this.isVisible = false;
        this.loadTable();
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 游戏添加
   */
  showAddGanmeModal(item: any) {
    // if (item.gameAppList?.length) {
    //   this.addGameIds = item.gameAppList.map((m: any) => m.id);
    // }
    this.editGameItems = item || {};
    this.isSelectVisible = true;
  }

  async submitGameData(ids: any) {
    const params = {
      id: this.editGameItems.id,
      gameIds: ids.join(',')
    }
    const {code, data, message}: any = await this.services.setGameTypeAddappData(params);

    if (code === 0) {
      this.msg.success('操作成功');
      this.loadTable();
    }
  }

  // 删除已关联应用
  async deleteRelationAppItem(item: any, gItem: any) {
    const params = {
      id: item.id, // 分类ID
      gameId: gItem.id // 游戏ID
    }
    const {code, data, message}: any = await this.services.deleteGameTypeAppData(params);

    if (code === 0) {
      this.msg.success('删除成功');
      this.loadTable();
    }
  }

  // 游戏上下移动
  async moveGameApp(item: any, currIndex: number, nextIndex: number) {
    const arrs = item.gameAppList || [];
    if (arrs?.length) {
      let tempArrs = arrs.map((m: any) => m.id);
      tempArrs[currIndex] = tempArrs.splice(nextIndex, 1, tempArrs[currIndex])[0]

      const params = {
        id: item.id, // 分类ID
        gameId: tempArrs.join(',') // 游戏ID
      }
      const {code}: any = await this.services.updateGameTypeAppSortData(params);

      if (code === 0) {
        this.msg.success('操作成功');
        this.loadTable();
      }
    }
  }
}
